<template>
  <el-dialog
    :visible.sync="dialogVisible"
    @close="handleClose"
    ref="publishDialog"
    width="60%"
    :title="dialogTitle"
  >
    <!-- 对话框内容 -->
    <el-form ref="form" :model="formData" label-width="100px">
      <!-- 根据数据对象动态生成表单项 -->
      <el-form-item
        v-for="(item, key) in formData"
        :label="formatLabel(key)"
        v-show="
          key !== 'document_url' &&
            key !== 'img_url' &&
            key !== 'imgList' &&
            key !== 'video_url'
        "
        :key="key"
      >
        <el-input
          v-model="formData[key]"
          v-if="key !== 'paid_product' && key !== 'cost'"
          :disabled="key === firstKey"
        ></el-input>
        <el-input-number
          v-else-if="key === 'cost'"
          :disabled="!formData.paid_product"
          v-model="formData[key]"
          :precision="2"
          :step="0.1"
        ></el-input-number>
        <el-switch
          v-model="formData[key]"
          v-else-if="key === 'paid_product'"
          active-color="#13ce66"
          inactive-color="#ff4949"
        >
        </el-switch>
      </el-form-item>
      <el-form-item prop="tag_ids" label="标签">
        <el-tag
          v-show="dynamicTags.length"
          :key="tag.id"
          v-for="tag in dynamicTags"
          closable
          :disable-transitions="false"
          @close="removeTag(tag)"
        >
          {{ tag.tag_name }}
        </el-tag>
        <el-button class="button-new-tag" size="small" @click="showTagDialog">
          <i class="el-icon-circle-plus-outline"></i>
          添加标签</el-button
        >
      </el-form-item>
      <el-form-item label="封面" v-if="type != 'document'" prop="img_url">
        <UploadImage :editUrl="formData.img_url" />
      </el-form-item>
      <el-form-item
        label="视频"
        style="margin-top:100px"
        v-if="type == 'video'"
        prop="video_url"
      >
        <UploadVideo :video_url="formData.video_url" />
      </el-form-item>
      <el-form-item label="文档" v-if="type == 'document'" prop="document_url">
        <UploadDocument :document_url="formData.document_url" />
      </el-form-item>
      <el-form-item
        label="乐谱"
        style="margin-top:100px"
        v-if="type == 'musicScore'"
        prop="document_url"
      >
        <UploadMusicScore :referenced_urls="formData.imgList" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <!-- 自定义确定按钮的事件 -->
      <el-button @click="handleConfirm" type="primary">确定</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
    <TagDialog
      :ShowTagDialogVisible="ShowTagDialogVisible"
      @closeTagDialog="closeTagDialog"
      :tag_ids="tag_ids"
    />
  </el-dialog>
</template>

<script>
import UploadImage from '@/components/Upload/UploadImage'
import UploadVideo from '@/components/Upload/UploadVideo'
import TagDialog from '@/components/Dialog/TagDialog'
import UploadDocument from '@/components/Upload/UploadDocument'
import UploadMusicScore from '@/components/Upload/UploadMusicScore'
export default {
  components: {
    UploadImage,
    TagDialog,
    UploadVideo,
    UploadDocument,
    UploadMusicScore
  },
  props: {
    data: {
      type: Object, // 传递的对象数据
      required: true
    },
    dialogTitle: {
      type: String, // 对话框标题
      default: '编辑'
    },
    visible: {
      type: Boolean,
      required: true
    },
    type: {
      type: String,
      required: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      formData: {}, // 表单数据对象
      cover_url: '', // 图片路径
      ShowTagDialogVisible: false,
      tag_ids: '',
      dynamicTags: [],
      firstKey: null,
      document_url: '',
      refrenced_urls: [],
      file_code: ''
    }
  },
  mounted() {},
  watch: {
    data: {
      // immediate: true,
      handler(newValue) {
        // 监听传递的对象数据，更新表单数据对象
        // 如果 newValue 对象有任何值，则进入编辑状态并禁止更改第一项
        // console.log('newvalue', Object.values(newValue))
        this.formData = { ...newValue }

        if (
          newValue.article_id ||
          newValue.video_id ||
          newValue.music_score_id ||
          newValue.document_id
        ) {
          this.isEdit = true
          this.getCurrentTagList(newValue)
          this.firstKey = Object.keys(this.formData)[0]
        } else {
          this.isEdit = false
          this.firstKey = null
        }
      }
    },
    visible: {
      immediate: true,
      handler(val) {
        this.dialogVisible = val
      }
    }
  },
  methods: {
    // 确认功能回调
    handleConfirm() {
      // 获取乐谱列表
      this.$bus.$emit('handleConfirm')

      const { type } = this
      this.img_url = this.$store.state.upload.img_url
      this.video_url = this.$store.state.upload.video_url
      this.document_url = this.$store.state.upload.document_url
      this.refrenced_urls = this.$store.state.upload.imgList
      console.log('confirmdocument', this.document_url)
      // 检查数据有效性
      if (!this.tag_ids) return this.$message.warning('请选择标签')

      // 获得标签id
      this.formData.tag_ids = this.tag_ids
      // 字段初始化
      this.formData.referenced_urls = []
      // 根据类型整理数据
      if (type == 'article') {
        this.formData.img_url = this.img_url
        this.formData.referenced_urls.push(this.img_url)
      } else if (type == 'video') {
        if (!this.video_url) return this.$message.warning('请上传视频')

        this.formData.img_url = this.img_url
        this.formData.video_url = this.video_url
        this.formData.referenced_urls.push(this.img_url)
        this.formData.referenced_urls.push(this.video_url)
      } else if (type == 'document') {
        if (!this.document_url) return this.$message.warning('请上传文档')
        this.formData.referenced_urls.push(this.document_url)
        this.formData.url = this.document_url
      } else if (type == 'musicScore') {
        this.file_code = this.$store.state.upload.file_code
        if (!this.file_code) return this.$message.error('存储数据失败')
        this.formData.file_code = this.file_code
        this.formData.img_url = this.img_url
        this.formData.paid_product = this.formData.paid_product ? 1 : 0
        if (!this.refrenced_urls) return this.$message.warning('请上传乐谱')
        this.formData.referenced_urls = this.refrenced_urls
        // 如果是免费的就将价格设置为0
        if (!this.formData.paid_product) this.formData.cost = 0
      }
      this.$emit('custom-confirm', this.formData)

      // 关闭对话框
      this.dialogVisible = false
    },
    // 编辑状态下获取tag列表
    async getCurrentTagList(item) {
      console.log('article', item)
      let res
      // 根据资源类型获得tag
      if (item.article_id) {
        res = await this.$API.tag.getArticleTags(item.article_id)
      } else if (item.video_id) {
        res = await this.$API.tag.getVideoTags(item.video_id)
      } else if (item.music_score_id) {
        res = await this.$API.tag.getMusicScoreTags(item.music_score_id)
      } else if (item.document_id) {
        res = await this.$API.tag.getDocumentTags(item.document_id)
      }
      if (res.status == 200) {
        const tagIds = res.data.map(tag => tag.id).join(',')
        this.tag_ids = tagIds
        this.dynamicTags = res.data
      }
    },
    handleClose() {
      // 初始化数据
      this.tag_ids = ''
      this.img_url = ''
      this.video_url = ''
      this.dynamicTags = []
      this.dialogVisible = false
      // 删除未删除的文件
      this.$emit('custom-close')
    },
    // 取消按钮的事件逻辑
    handleCancel() {
      if (this.type == 'document') {
        this.$bus.$emit(
          'RemoveUploadFile',
          this.$store.state.upload.document_url
        )
      } else if (this.type == 'musicScore') {
        this.$bus.$emit('RemoveAlreadyUploadImage')
      } else if (this.type == 'video') {
        this.$bus.$emit('RemoveUploadVideo', this.$store.state.upload.video_url)
      }
      // 初始化数据
      this.tag_ids = ''
      this.img_url = ''
      this.video_url = ''
      this.dynamicTags = []
      this.dialogVisible = false
      // 删除未删除的文件
      this.$emit('custom-close')
    },
    // 删除tag
    removeTag(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      let tagList = this.tag_ids.split(',')
      console.log(tag)
      this.tag_ids = tagList
        .filter(t => {
          return tag.id != t
        })
        .join(',')
    },
    // 美化label
    formatLabel(key) {
      // 根据需要进行字段名到中文 label 的映射
      const labelMap = {
        title: '标题',
        content: '内容',
        cost: '价格',
        paid_product: '是否付费'
        // 其他字段...
      }

      // 根据字段名从映射表中获取对应的中文 label
      const formattedLabel = labelMap[key] || key
      return formattedLabel
    },
    // 关闭tag窗口回调
    closeTagDialog() {
      this.ShowTagDialogVisible = false
    },
    // 打开列表
    showTagDialog() {
      this.ShowTagDialogVisible = true
      // 监听获得tags_id事件
      this.$bus.$on('getTagsId', this.getTagList)
    },
    // 获取tag列表
    getTagList(item) {
      this.tag_ids = item.tags_id
      // 重置数组
      this.dynamicTags = []
      let tagList = []
      item.tagList.forEach(tag => {
        tagList.push(tag)
      })
      this.dynamicTags.push(...tagList)
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style>
